<template>
    <splitpanes class="default-theme" @resize="paneSize = $event[0].size" style="height: calc(100vh - 95px)">
        <pane :size="16">
            <OrganTreeSelect @nodeClick="onNodeClick" />
        </pane>
        <pane :size="84">
            <div class="table-box">
                <ProTable ref="proTable" :requestApi="getList" :initParam="initParam" :columns="columns"
                    :initData="false">
                    <!-- 表格 header 按钮 -->
                    <template #tableHeader="scope">
                        <el-button type="primary" :icon="CirclePlus" @click="openUserDialog('新增')">新增用户</el-button>
                        <el-button type="primary" :icon="Upload" plain @click="batchAdd">批量添加用户</el-button>
                        <el-button type="primary" :icon="Download" plain @click="downloadFile">导出用户数据</el-button>
                        <el-button type="danger" :icon="Delete" plain :disabled="!scope.isSelected"
                            @click="batchDelete(scope.ids)">
                            批量删除用户
                        </el-button>
                    </template>
                    <!-- Expand -->
                    <template #expand="scope">
                        {{ scope.row }}
                    </template>
                    <!-- 用户状态 slot -->
                    <template #dataStatus="scope">
                        <!-- 如果插槽的值为 el-switch，第一次加载会默认触发 switch 的 @change 方法，所有在外层包一个盒子，点击触发盒子 click 方法 -->
                        <div @click="changeStatus(scope.row)">
                            <el-switch :value="scope.row.locked" :active-text="scope.row.locked === '1' ? '锁定' : '正常'"
                                active-value="0" inactive-value="1" />
                        </div>
                    </template>
                    <!-- 表格操作 -->
                    <template #operation="scope">
                        <el-button type="primary" link :icon="View" @click="openUserDialog('查看', scope.row)">查看
                        </el-button>


                        <el-dropdown>
                            <span class="el-dropdown-link" style="margin-left:8px;f">
                                <el-button type="primary" size="small" text style="font-size:14px;">
                                    其它操作<el-icon class="el-icon--right">
                                        <ArrowDown />
                                    </el-icon>
                                </el-button>
                            </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item>
                                        <el-button type="primary" link :icon="EditPen"
                                            @click="openUserDialog('编辑', scope.row)">编辑
                                        </el-button>
                                    </el-dropdown-item>
                                    <el-dropdown-item>
                                        <el-button type="primary" link :icon="Delete"
                                            @click="deleteAccount(scope.row)">删除
                                        </el-button>
                                    </el-dropdown-item>
                                    <el-dropdown-item>
                                        <el-button type="primary" link :icon="UserFilled"
                                            @click="openUserRoleDialog(scope.row)">角色
                                        </el-button>
                                    </el-dropdown-item>
                                    <el-dropdown-item>
                                        <el-button type="primary" link :icon="Discount" @click="onAuth(scope.row)">
                                            授权</el-button>
                                    </el-dropdown-item>
                                    <el-dropdown-item>
                                        <el-button type="primary" link :icon="Refresh"
                                            @click="resetPass(scope.row)">重置</el-button>
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </template>
                </ProTable>
            </div>
        </pane>
    </splitpanes>
    <UserDialog ref="userDialogRef" />
    <UserRoleDialog ref="userRoleDialogRef" />
    <ImportExcel ref="importDialogRef" />
</template>

<script setup lang="tsx" name="user">
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { useHandleData } from "/@/hooks/useHandleData";
import { useDownload } from "/@/hooks/useDownload";
import UserDialog from "./components/UserDialog.vue";
import UserRoleDialog from "./components/UserRoleDialog.vue";
import OrganTreeSelect from "/@/components/OrganTreeSelect/index.vue";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh, UserFilled, Discount, ArrowDown } from "@element-plus/icons-vue";
import { getList, changeUserLocked, addUser, batchAddUser, editUser, deleteUser, resetUserPassWord } from "/@/api/auth/user";
import columnsFunction from './columns';
import ProTable from "/@/components/ProTable/index.vue";
import ImportExcel from "/@/components/ImportExcel/index.vue";
import { useRoute, useRouter } from 'vue-router';
import { Splitpanes, Pane } from 'splitpanes';
import 'splitpanes/dist/splitpanes.css';

const route = useRoute();
const router = useRouter();
const paneSize = ref(50);
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();

// 如果表格需要初始化请求参数,直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上)
const initParam = reactive({
    type: 1,
    sort: 'au.create_time',
    chain: '',
});

const onNodeClick = (data: any) => {
    initParam.chain = data.chain
    proTable.value.refresh();
}

/**
 * 授权
 */
const onAuth = (params: any) => {
    router.push({
        path: '/auth/permissionRelation',
        query: { targetId: params.id, status: 2, title: params.name },
    })
}

// 自定义渲染头部(使用tsx语法)
const renderHeader = (scope: any) => {
    return (
        <el-button
            type="primary"
            onClick={() => {
                console.log(scope);
                ElMessage.success("我是自定义表头");
            }}
        >
            {scope.row.label}
        </el-button>
    );
};

const columns = columnsFunction(renderHeader);



// 删除用户信息
const deleteAccount = async (params: any) => {
    await useHandleData(deleteUser, { id: params.id }, `删除【${params.username}】用户`);
    proTable.value.refresh();
};

// 批量删除用户信息
const batchDelete = async (ids: string[]) => {
    await useHandleData(deleteUser, { ids }, "删除所选用户信息");
    proTable.value.refresh();
};

// 重置用户密码
const resetPass = async (params: any) => {
    await useHandleData(resetUserPassWord, { id: params.id }, `重置【${params.username}】用户密码`);
    // proTable.value.refresh();
};

//切换用户状态
const changeStatus = async (row: any) => {
    await useHandleData(changeUserLocked, { id: row.id, locked: row.locked === '1' ? '0' : '1' }, `切换【${row.username}】用户状态`);
    // proTable.value.refresh();
};

// 导出用户列表
const downloadFile = async () => {
    useDownload(getList, "用户列表", proTable.value.searchParam);
};

// 批量添加用户
interface ImportDialogExpose {
    acceptParams: (params: any) => void;
}
const importDialogRef = ref<ImportDialogExpose>();
const batchAdd = () => {
    let params = {
        title: "用户",
        tempApi: getList,
        importApi: batchAddUser,
        getTableList: proTable.value.refresh
    };
    importDialogRef.value!.acceptParams(params);
};

// 打开 dialog(新增、查看、编辑)
interface UserDialogExpose {
    acceptParams: (params: any) => void;
}
const userDialogRef = ref<UserDialogExpose>();
const openUserDialog = (title: string, rowData = {}) => {
    let params = {
        title: title,
        rowData: { ...rowData },
        isView: title === "查看" ? true : false,
        apiUrl: title === "新增" ? addUser : title === "编辑" ? editUser : "",
        getTableList: proTable.value.refresh
    };
    userDialogRef.value!.acceptParams(params);
};

const userRoleDialogRef = ref<UserDialogExpose>();
const openUserRoleDialog = (rowData: any = {}) => {
    let params = {
        title: '用户角色管理',
        rowData: { userId: rowData.id, roleIds: rowData.roleIds },
        getTableList: proTable.value.refresh
    };
    userRoleDialogRef.value!.acceptParams(params);
};

</script>
<style lang="scss" scoped>
.table-box {
    display: flex;
    width: 100%;
    flex-direction: row;

    .table-left {
        display: flex;
        width: 200px;
        flex-direction: column;

    }

    .table-right {
        display: flex;
        flex: 1 1 0;
        overflow: hidden;
        padding-left: 12px;
    }
}
</style>